package cn.yingtian.image;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class ImageLoader {

	private static final ImageLoader loader = new ImageLoader();

	private ImageLoader() {
	}

	public static ImageLoader newInstance() {
		return loader;
	}

	public void loadImage(final String url, final ImageLoaderCallBack callBack) {
		boolean hasSD = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);

		if (!hasSD) {
			return;
		}
		if (!Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			return;
		}
		String foldername = Environment.getExternalStorageDirectory().getPath()+ "/image";
		 final File folder = new File(foldername);

		if (folder == null || !folder.exists()) {
			folder.mkdirs();
		}

		final Handler handler = new Handler() {

			public void handleMessage(Message message) {
				callBack.imageLoaded((Uri) message.obj, url);
			}
		};
		new Thread() {

			@Override
			public void run() {

				
				File file = new File(folder, MD5.getMD5(url));
				if(!file.exists()){
					FileOutputStream fos = null;
					try {
						byte data[] = NetWorkTools.getData(MainActivity.SERVER_NAME+url);
						System.out.println(url+":----:"+data.length);
						fos = new FileOutputStream(file);
						fos.write(data);
						fos.flush();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						if (fos != null) {
							try {
								fos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
					}
				}

				Message message = handler.obtainMessage(0, Uri.fromFile(file));

				handler.sendMessage(message);
			}
		}.start();

	}
}
